/**
 * 字符串转换成Uint8Array
 * @param {string | buffer} str
 * @return
 */
function strToUnit8Array(str) {
  if (typeof str === 'string') {
    const arr = [];
    str.split(' ').forEach(item => {
      arr.push(parseInt(item, 16));
    });
    return Uint8Array.from(arr);
  } else if (Buffer.isBuffer(str)) {
    return str;
  }
}

// 字符串长度判断不足填充0
function fillZero(num, n) {
  let len = num.toString().length;
  while (len < n) {
    num = '0' + num;
    len++;
  }
  return num;
}

/**
 * BCC校验
 * @param {string} hexStr
 */
function chk8xor(hexStr) {
  let bcc = 0;
  let xor = 0;

  const hexArr = hexStr.trim().split(' ');
  for (let i = 0; i < hexArr.length; i++) {
    const hexInt = parseInt(hexArr[i], 16);
    if (i === 0) {
      xor = hexInt;
    } else {
      // eslint-disable-next-line no-bitwise
      bcc = xor ^ hexInt;
      xor = bcc;
    }
  }
  return fillZero(bcc.toString(16), 2).toUpperCase();
}

/**
 * 16进制转10进制
 * @param hex
 * @returns {any}
 */
function hex2Int(hex) {
  const len = hex.length;
  const a = new Array(len);
  let code;
  for (let i = 0; i < len; i++) {
    code = hex.charCodeAt(i);
    if (48 <= code && code < 58) {
      code -= 48;
    } else {
      code = (code & 0xdf) - 65 + 10;
    }
    a[i] = code;
  }

  return a.reduce(function (acc, c) {
    acc = 16 * acc + c;
    return acc;
  }, 0);
}

/**
 * 10进制转16进制
 * @param {numBer} num 数值
 * @param {numBer} width 位数
 * @returns {string}
 */
function int2Hex(num, width) {
  const hex = '0123456789abcdef';
  let s = '';
  while (num) {
    s = hex.charAt(num % 16) + s;
    num = Math.floor(num / 16);
  }
  if (typeof width === 'undefined' || width <= s.length) {
    return '0x' + s;
  }
  let delta = width - s.length;
  let padding = '';
  while (delta-- > 0) {
    padding += '0';
  }
  return '0x' + padding + s;
}

/**
 * 转换总站编码为"00 01"的形式
 * @param {number} station
 */
function transformStationCode(station) {
  const str = station.toString().padStart(4, '0');
  const arr = str.split('');
  arr.splice(2, 0, ' ');
  return arr.join('');
}

module.exports = {
  strToUnit8Array,
  chk8xor,
  hex2Int,
  int2Hex,
  transformStationCode,
};
